<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" fixed />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image round class="avatar" :src="profileObj.photo" @click="selectPhoto"/>
          <input type="file" hidden ref="photo" @change="uploadPhoto">
        </template>
      </van-cell>
      <van-cell title="名称" is-link :value="profileObj.name" @click="show1 = true"/>
      <van-dialog
      v-model="show1"
      show-cancel-button
      title="修改名称"
      :before-close="onBeforeClose"
      >
        <van-field
        v-focus
        v-model.trim="profileObj.name"
        placeholder="请输入姓名"
        ></van-field>
      </van-dialog>
      <van-cell title="性别" is-link :value="profileObj.gender === 1 ? '男' : '女'" />
      <van-cell title="生日" is-link :value="profileObj.birthday" @click="show2 = true"/>
      <!-- 修改时间 -->
      <van-popup v-model="show2" position="bottom" style="height: 50%" round>
      <!-- 日期选择控件 -->
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择出生日期"
        :min-date="minDate"
        :max-date="maxDate"
        :show-toolbar="true"
        @confirm="updateBirthday"
        @cancel="show2 = false"
      />
</van-popup>
    </van-cell-group>
  </div>
</template>

<script>
import { userEditAPI, updatephotoAPI, updateuserInfoAPI } from '@/api/user'
import { formatDate } from '@/utils/moment'
export default {
  name: 'UserEdit',
  data () {
    return {
      profileObj: {}, // 用户信息
      show1: false,
      show2: false, // 显示时间选择器
      minDate: new Date(1900, 0, 1), // 最小的可选的日期
      maxDate: new Date(), // 最大的可选日期
      currentDate: new Date() // 当前日期
    }
  },
  async created () {
    // 页面初始数据铺设
    const res = await userEditAPI()
    // console.log(res)
    this.profileObj = res.data
    this.currentDate = new Date(this.profileObj.birthday)
  },
  methods: {
    // 改生日
    async updateBirthday (value) {
      const birthday = formatDate(value)
      try {
        await updateuserInfoAPI({
          name: this.profileObj.name,
          birthday
        })
        this.profileObj.birthday = birthday
        this.$toast.success('修改成功')
      } catch {
        this.$toast.fail('修改失败')
      } finally {
        this.show2 = false
      }
    },
    // 改名字
    async onBeforeClose (action, done) {
      if (action === 'cancel') {
        done()
        return
      }
      if (!this.profileObj.name) {
        done(false)
        this.$toast.fail('不能为空')
        return
      }
      if (!/^[a-z\d\u4e00-\u9fa5]{1,7}$/i.test(this.profileObj.name)) {
        done(false)
        this.$toast.fail('姓名不合法')
        return
      }
      try {
        await updateuserInfoAPI({
          name: this.profileObj.name,
          birthday: this.profileObj.birthday
        })
        this.$store.commit('user/setUserInfo', { name: this.profileObj.name })
        this.$toast.success('修改成功')
      } catch (error) {
        this.$toast.fail('修改失败')
      } finally {
        done()
      }
    },
    // 把文件上传到文件域
    selectPhoto () {
      const el = this.$refs.photo
      el.click()
    },
    // 上传头像
    async uploadPhoto (e) {
      // 文件对象
      const { 0: file } = e.target.files
      const { size, name } = file
      if (!/\.(png|jpe?g|webp|gif|svg)$/i.test(name)) return this.$toast.fail('请上传图片文件')
      if (size / 1024 / 1024 > 2) return this.$toast.fail('请上传小于2M图片文件')
      const formDate = new FormData()
      formDate.append('photo', file)
      // 调接口
      const res = await updatephotoAPI({
        formDate
      })
      this.profileObj.photo = res.data.photo
      // 将用户修改后的头像地址保存在vuex中(性能优化)
      this.$store.commit('user/setUserInfo', {
        photo: res.data.photo
      })
    }

  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
